package com.uniledger.exchange.push;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.content.ContextCompat;

import com.uniledger.exchange.HomeActivity;
import com.uniledger.exchange.R;
import com.uniledger.exchange.welcome.WelcomeActivity;

public class NotifyUtil {

    public static final int NOTIFICATION_TRANSFER_USER_ID = 888;//扫码转账
    public static final int NOTIFICATION_TRANSFER_SCAN_ID = 888;//用户间转账

    private static NotificationManagerCompat mNotificationManagerCompat;

    /**
     * 初始化推送管理器
     *
     * @param context
     */
    public static void init(Context context) {
        mNotificationManagerCompat = NotificationManagerCompat.from(context);
    }

    /**
     * 判断是否可以接收推送通知展示
     *
     * @return
     */
    public static boolean areNotificationsEnabled() {
        return mNotificationManagerCompat.areNotificationsEnabled();
    }

    /**
     * 打开通知设置栏
     *
     * @param activity
     */
    private static void openNotificationSettingsForApp(Activity activity) {
        // Links to this app's notification settings.
        Intent intent = new Intent();
        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
        intent.putExtra("app_package", activity.getPackageName());
        intent.putExtra("app_uid", activity.getApplicationInfo().uid);
        activity.startActivity(intent);
    }


    public static void sendMessagingStyleNotification(Context context, MockPush mockPush) {
        // Main steps for building a MESSAGING_STYLE notification:
        //TODO      0. Get your data

        //TODO      1. Create/Retrieve Notification Channel for O and beyond devices (26+)
        String notificationChannelId = createTransferNotificationChannel(context, mockPush);

        //      2. Build the MESSAGING_STYLE
        NotificationCompat.MessagingStyle messagingStyle =
                new NotificationCompat.MessagingStyle(mockPush.userDisplayName);

        messagingStyle.setConversationTitle(mockPush.contentTitle);

        NotificationCompat.MessagingStyle.Message message =
                new NotificationCompat.MessagingStyle.Message(mockPush.contentText, mockPush.timestamp, mockPush.sender);
        messagingStyle.addMessage(message);

        //      3. Set up main Intent for notification
        Intent notifyIntent = new Intent(context, WelcomeActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        // Adds the back stack
        stackBuilder.addParentStack(HomeActivity.class);
        // Adds the Intent to the top of the stack
        stackBuilder.addNextIntent(notifyIntent);
        // Gets a PendingIntent containing the entire back stack
        PendingIntent mainPendingIntent =
                PendingIntent.getActivity(
                        context,
                        0,
                        notifyIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );

        //      4. Set up RemoteInput (users can input directly from notification)


        //      5. Build and issue the notification


        NotificationCompat.Builder notificationCompatBuilder =
                new NotificationCompat.Builder(context, notificationChannelId);

        GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);


        notificationCompatBuilder
                // MESSAGING_STYLE sets title and content for API 16 and above devices.
                .setStyle(messagingStyle)
                // Title for API < 16 devices.
                .setContentTitle(mockPush.contentTitle)
                // Content for API < 16 devices.
                .setContentText(mockPush.contentText)
                .setTicker("")//首次进入时显示效果
                .setAutoCancel(true)
                .setSmallIcon(R.mipmap.ic_launcher)
                //.setLargeIcon(BitmapFactory.decodeResource(
                //               getResources(),
                //       R.drawable.ic_person_black_48dp))
                .setContentIntent(mainPendingIntent)
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                // Set primary color (important for Wear 2.0 Notifications).
                .setColor(ContextCompat.getColor(context, R.color.colorPrimary))

                // SIDE NOTE: Auto-bundling is enabled for 4 or more notifications on API 24+ (N+)
                // devices and all Wear devices. If you have more than one notification and
                // you prefer a different summary notification, set a group key and create a
                // summary notification via
                // .setGroupSummary(true)
                // .setGroup(GROUP_KEY_YOUR_NAME_HERE)

                // Number of new notifications for API <24 (M and below) devices.
                .setSubText(Integer.toString(mockPush.numberOfNewMessages))

                //.addAction(replyAction)
                .setCategory(Notification.CATEGORY_MESSAGE)
                // Sets priority for 25 and below. For 26 and above, 'priority' is deprecated for
                // 'importance' which is set in the NotificationChannel. The integers representing
                // 'priority' are different from 'importance', so make sure you don't mix them.
                // .setPriority(messagingStyleCommsAppData.getPriority())

                // Sets lock-screen visibility for 25 and below. For 26 and above, lock screen
                // visibility is set in the NotificationChannel.
                .setVisibility(mockPush.channelLockScreenVisibility)
                .setLights(Color.RED, 1000, 1000)
                .setVibrate(new long[]{0, 400, 250, 400})
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
        ;
        Notification notification = notificationCompatBuilder.build();
        send(mockPush.nid, notification);
    }

    /**
     * 发送消息
     *
     * @param id
     * @param notification
     */
    private static void send(int id, Notification notification) {
        mNotificationManagerCompat.notify(id, notification);
    }

    /**
     * 取消通知
     *
     * @param id
     */
    public static void cancel(int id) {
        mNotificationManagerCompat.cancel(id);
    }

    /**
     * 取消同类消息通知
     *
     * @param tag
     * @param id
     */
    public static void cancel(String tag, int id) {
        mNotificationManagerCompat.cancel(tag, id);
    }

    /**
     * 取消全部通知
     */
    public static void cancelAll() {
        mNotificationManagerCompat.cancelAll();
    }

    private static String createTransferNotificationChannel(
            Context context,
            MockPush mockPush) {
        // NotificationChannels are required for Notifications on O (API 26) and above.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //TODO Initializes NotificationChannel.

            String channelId = mockPush.channelId;

            NotificationChannel notificationChannel =
                    new NotificationChannel(channelId, "Transfer", NotificationManager.IMPORTANCE_HIGH);
            notificationChannel.setDescription("");

            notificationChannel.enableLights(true); //是否在桌面icon右上角展示小红点
            notificationChannel.setLightColor(Color.GREEN); //小红点颜色
            notificationChannel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知

            notificationChannel.enableVibration(true);
            notificationChannel.setLockscreenVisibility(mockPush.channelLockScreenVisibility);
            // Adds NotificationChannel to system. Attempting to create an existing notification
            // channel with its original values performs no operation, so it's safe to perform the
            // below sequence.
            NotificationManager notificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);

            return channelId;
        } else {
            // Returns null for pre-O (26) devices.
            return null;
        }
    }

}
